package com.aldobucchi.x.flash.events
{
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.events.Event;

/**
 *  
 * 
 *  @eventType mx.events.Event
 */
[Event(name="complete", type="flash.events.Event")]

	
	/**
	 * Will fire a Event.COMPLETE event when all the dispatchers have fired
	 * their respective "eventType" event
	 * 
	 * DO NOT ADD TWO IDENTICAL PAIRS ( not tested yet )
	 * 
	 * @author aldo.bucchi@gmail.com
	 * 
	 */	
	public class EventJoin extends EventDispatcher
	{
	
		private var total:int 	= 0;
		private var counter:int = 0;
	
		/**
		 * 
		 * @param dispatcherEventPairs in the format [ [eventDispatcher1,"eventType1"] , [eventDispatcher2,"eventType2"] ,...]
		 * 
		 */
		public function EventJoin( dispatcherEventPairs:Array )
		{	
			total = dispatcherEventPairs.length;
			for each ( var pair:Array in dispatcherEventPairs )
				( pair[0] as IEventDispatcher )
					.addEventListener( pair[1] as String, handleEvent );
		}
		
		private function handleEvent( event:Event ):void
		{
			counter++;
			// trace( "EventJoin.handleEvent() [" + counter + "/" + total + "] event.target = " + event.target.toString() );
			if ( counter == total )
				dispatchEvent( new Event( Event.COMPLETE ) );
		}
	
	}
	
}